package cn.usian.filter;

import cn.usian.common.R;
import com.alibaba.fastjson.JSON;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    private boolean checkurl(String[]urls,String requestURI){
        for (String url : urls) {
            if(antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //加协议
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        //获取本次请求的url
        String requestURI = request.getRequestURI();
        //定义数组存储url，判断本次登录是否需要权限
        String[]urls={"/backend/**","/front/**","/employee/login"};
        boolean flag = checkurl(urls, requestURI);
        if(flag){
            filterChain.doFilter(request,response);
            return;
        }
        HttpSession session = request.getSession();
        if(session.getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            return;
        }

        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);

    }
}
